﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Web;
using System.Web.Mvc;

namespace Smarly.Web.ActionFilters
{
	public class PartialCacheAttribute : ActionFilterAttribute
	{
		private string _name;
		private string _staticPartial;
		public PartialCacheAttribute(string name, string staticPartial)
		{
			_name = name;
			_staticPartial = staticPartial;
		}

		private Dictionary<string, Dictionary<string, MvcHtmlString>> dir = new Dictionary<string, Dictionary<string, MvcHtmlString>>(); 
		#region Overrides of ActionFilterAttribute

		#region Overrides of ActionFilterAttribute

		public override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			var viewData = filterContext.Controller.ViewData;
			var tempData = filterContext.Controller.TempData;

			Dictionary<string, MvcHtmlString> action = null;

			if (!dir.ContainsKey(_name))
			{
				action = new Dictionary<string, MvcHtmlString>();
				dir.Add(_name, action);
			}

			action = action ?? dir[_name];

			MvcHtmlString partial = null;

			if (!action.ContainsKey(_staticPartial))
			{
				using (StringWriter sw = new StringWriter())
				{
					ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(filterContext, _staticPartial);
					ViewContext viewContext = new ViewContext(filterContext, viewResult.View, viewData, tempData, sw);
					viewResult.View.Render(viewContext, sw);

						partial = new MvcHtmlString(sw.GetStringBuilder().ToString());
					action.Add(_staticPartial, partial);
				}
			}

			viewData[_staticPartial] = partial ?? action[_staticPartial];
			

			base.OnActionExecuted(filterContext);
		}

		public override void OnResultExecuting(ResultExecutingContext filterContext)
		{
			if (dir.Count > 0)
				return;
			base.OnResultExecuting(filterContext);
		}

		#endregion

		public override void OnResultExecuted(ResultExecutedContext filterContext)
		{
			if (dir.Count > 0)
				return;
			base.OnResultExecuted(filterContext);
		}

		#endregion
	}

}